package com.hyfd.task;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hyfd.common.utils.ToolDateTime;
import com.hyfd.common.utils.XmlUtils;
import com.hyfd.dao.mp.OrderDao;
import com.hyfd.dao.mp.ProviderPhysicalChannelDao;
import com.hyfd.deal.Flow.YunXuFlowDeal;
import com.hyfd.rabbitMq.RabbitMqProducer;
import com.hyfd.rabbitMq.SerializeUtil;

@Component
public class YunXuFlowTask
{
    
    static Logger log = Logger.getLogger(YunXuFlowDeal.class);
    
    @Autowired
    OrderDao orderDao;
    
    @Autowired
    RabbitMqProducer mqProducer;// 消息队列生产者
    
    @Autowired
    ProviderPhysicalChannelDao providerPhysicalChannelDao;// 物理通道信息
    
    // @Scheduled(fixedDelay = 60000)
    public void queryZhiTongOrder()
    {
        Map<String, Object> map = new HashMap<String, Object>();
        int flag = 2;
        try
        {
            String providerId = "0000000074";//
            Map<String, Object> channel = providerPhysicalChannelDao.selectByProviderId(providerId);// 获取通道
            String defaultParameter = (String)channel.get("default_parameter");// 参数
            Map<String, String> paramMap = XmlUtils.readXmlToMap(defaultParameter);
            String username = paramMap.get("username");// 登录账户
            String password = paramMap.get("password");// 登录密码
            String linkUrl = paramMap.get("queryUrl");// 查询url
            String key = paramMap.get("key");// 接口密钥
            
            // 查询订单中属于指通的折扣
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("dispatcherProviderId", providerId);
            param.put("status", "1");
            List<Map<String, Object>> orderList = orderDao.selectByTask(param);// 查询出所有尚通的充值中的订单
            for (int i = 0, size = orderList.size(); i < size; i++)
            {
                Map<String, Object> order = orderList.get(i);
                String orderId = order.get("orderId") + "";// 平台订单号
                map.put("orderId", orderId);
                String result = rechargeFlow(linkUrl, username, password, key, orderId);
                JSONObject jsonObject = JSON.parseObject(result);
                String code = jsonObject.getString("code");
                String msg = jsonObject.getString("msg");
                map.put("resultCode", code + ":" + msg);
                if (code.equals("111111"))
                {// 提交成功
                    flag = 1;
                    /*
                     * JSONObject data = jsonObject.getJSONObject("data"); String outTrNo =
                     * data.getString("outTradeNo"); String sysOrderId = data.getString("sysOrderId");
                     * map.put("orderId", outTrNo); map.put("providerOrderId", sysOrderId);
                     */
                }
                else if (code.equals("000000"))
                {
                    continue;
                }
                else
                {
                    flag = 0;
                }
                map.put("status", flag);
                mqProducer.sendDataToQueue(RabbitMqProducer.Result_QueueKey, SerializeUtil.getStrFromObj(map));
            }
        }
        catch (Exception e)
        {
            log.error("云旭流量查询出错" + e);
        }
    }
    
    // 充值接口
    public static String rechargeFlow(String linkUrl, String username, String password, String key, String orderid)
    {
        String timestamp = ToolDateTime.format(new Date(), "yyyyMMddHHmmss");
        String type = "1";
        String sign = md5(username + password + orderid + key, 32);
        // 设置请求参数
        Map<String, String> pMap = new HashMap<String, String>();
        // 用户名称
        pMap.put("username", username);
        // 用户密码
        pMap.put("password", password);
        // 订单编号
        pMap.put("orderid", orderid);
        // 签名
        pMap.put("sign", sign);
        log.error("请求参数:" + pMap);
        NameValuePair[] data =
            {new NameValuePair("username", username), new NameValuePair("password", password),
                new NameValuePair("orderid", orderid), new NameValuePair("sign", sign)// 签名认证
            };
        return post(linkUrl, data);
    }
    
    /**
     * Http请求工具类
     */
    public static String post(String url, NameValuePair[] data)
    {
        
        HttpClient httpClient = new HttpClient();
        PostMethod method = new PostMethod(url);
        httpClient.getParams().setContentCharset("UTF-8");
        method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
        method.setRequestBody(data);
        String result = "";
        try
        {
            int ret = httpClient.executeMethod(method);
            if (ret == 200)
            {
                result = method.getResponseBodyAsString();
            }
            else
            {
                result = "{\"code\":\"-1\",\"msg\":\"请求超时," + ret + "。\"}";
            }
            
        }
        catch (HttpException e)
        {
            result = "{\"code\":\"-1\",\"msg\":\"请求超时,HttpException。\"}";
        }
        catch (IOException e)
        {
            result = "{\"code\":\"-1\",\"msg\":\"数据错误，IOException。\"}";
        }
        return result;
    }
    
    /**
     * md5加密
     * 
     * @param strSrc 加密原串
     * @return 加密后的值
     * @throws Exception
     */
    public static String md5(String strSrc, int len)
    {
        String result = "";
        MessageDigest md5;
        try
        {
            md5 = MessageDigest.getInstance("MD5");
            System.out.println(strSrc);
            md5.update(strSrc.getBytes("utf-8"));
            byte[] temp;
            temp = md5.digest();
            for (int i = 0; i < temp.length; i++)
            {
                result += Integer.toHexString((0x000000ff & temp[i]) | 0xffffff00).substring(6);
            }
        }
        catch (NoSuchAlgorithmException e)
        {
            log.error("NoSuchAlgorithmException");
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result.substring(0, len);
    }
    
    public static void main(String[] args)
    {
        Map<String, Object> m = new HashMap<String, Object>();
        m.put("value", "10.000");
        double d = Double.parseDouble(m.get("value") + "");
        int i = (int)d;
        String s = i + "";
        
        System.out.println(i + "\t" + d + "\t" + s);
    }
}
